$(function() {

	// input监听器
	$("#btn").on("click", function() {

		var url = "http://localhost:3000/users";
		getUsers(url);
	});

	// get users list
	function getUsers(url) {

		$.ajax({
			url : 'http://localhost:3000/users',
			type : 'GET',
			dataType : "json"
		}).done(function(msg) {
			tableOperator($("tbody"), msg).createTable();
		}).fail(function(msg) {
		});
	}
	;

	//delete user by id
	function deleteUser(id) {

//		console.log(id);
		$.ajax({
			url : 'http://localhost:3000/users/' + id,
			type : 'DELETE',
			dataType : "json"
		}).done(function(msg) {
			getUsers();
		}).fail(function(msg) {
		});
	}
	;

	//load data
	function tableOperator(tbody, data) {

		var obj = {};
		obj.createTable = function() {
			tbody.empty();
			for ( var i in data) {
				var tr = $("<tr></tr>");
				var td1 = $("<td></td>");
				var td2 = $("<td></td>");
				var td3 = $("<td></td>");
				var td4 = $("<td></td>");
				var delBtn = $("<button></button>");
				delBtn.text('delete').attr("id", data[i].id).attr("class","button").click(function() {
					deleteUser($(this).attr("id"));
				});
				td1.text(data[i].id);
				td2.text(data[i].name);
				td3.text(data[i].age);
				td4.append(delBtn);
				tr.append(td1);
				tr.append(td2);
				tr.append(td3);
				tr.append(td4);
				tbody.append(tr);
			}
		};
		return obj;
	}

});